<script setup>
import api from "../utils/axios.js";
import {useRouter} from "vue-router";
import {ElNotification} from "element-plus";

const router = useRouter()
const user = reactive({
  name: undefined,
  role: undefined
})

const emit = defineEmits(['emit-role'])

function logout() {
  api({
    method: "delete",
    url: "api/session"
  }).then(() => {
    sessionStorage.removeItem("token")
    ElNotification({
      title: "退出登录成功",
      message: "请稍等，正在跳转至登录页",
      duration: 2000,
      type: 'success',
      onClose: () => {
        router.push("/login")
      }
    })
  }).catch(error => {
    ElNotification({
      title: error.code,
      message: error.message,
      duration: 0,
      type: 'error'
    })
  })
}

onMounted(() => {
  api({
    method: "get",
    url: "api/user"
  }).then(response => {
    user.name = response.data.name
    user.role = response.data.role
    emitRole(user.role)
  }).catch(error => {
    ElNotification({
      title: error.code,
      message: error.message,
      duration: 0,
      type: 'error'
    })
  })
})

const userRole = computed(() => {
  switch (user.role) {
    case 0:
      return "管理员"
    case 1:
      return "学生"
    case 2:
      return "教师"
    case 3:
      return "教务员"
  }
})

const userName = computed(() => {
  return user.name
})

function emitRole(role) {
  emit('emit-role', role)
}

</script>

<template>
  <div class="w-full h-[70px]">
    <div class="h-full flex flex-row items-center justify-between">
      <div>
        <span class="text-[2rem] font-bold">学生成绩管理系统</span>
      </div>
      <div class="flex flex-row items-center gap-5">
        <el-avatar>
          <IEpUserFilled class="text-2xl"/>
        </el-avatar>
        <el-dropdown trigger="click">
					<span class="el-dropdown-link text-base">
            欢迎您！{{ userRole }}, {{ userName }}
						<el-icon>
							<IEpArrowDown/>
						</el-icon>
					</span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>